const express = require('express')
const router = express.Router()
const { pool } = require('../config/db.js')
const auth = require('../middleware/auth.js')
const { deepseekService } = require('../services/deepseek.js')
const Chat = require('../../models/Chat.js')

// 获取聊天历史
router.get('/history', auth, async (req, res) => {
  try {
    const connection = await pool.getConnection()
    try {
      const [chats] = await connection.query(
        `SELECT c.*,
                (SELECT COUNT(*) FROM messages WHERE chat_id = c.id) as message_count,
                (SELECT content FROM messages WHERE chat_id = c.id ORDER BY created_at ASC LIMIT 1) as first_message
         FROM chats c
         WHERE user_id = ?
         ORDER BY updated_at DESC`,
        [req.user.userId]
      )
      res.json({
        code: 200,
        message: '获取成功',
        success: true,
        data: chats
      })
    } finally {
      connection.release()
    }
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 获取聊天消息
router.get('/:chatId/messages', auth, async (req, res) => {
  try {
    const connection = await pool.getConnection()
    try {
      const [messages] = await connection.query(
        'SELECT * FROM messages WHERE chat_id = ? ORDER BY created_at ASC',
        [req.params.chatId]
      )
      res.json({
        code: 200,
        message: '获取成功',
        success: true,
        data: messages
      })
    } finally {
      connection.release()
    }
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: err.message,
      success: false
    })
  }
})

// 发送消息
router.post('/message', auth, async (req, res) => {
  try {
    const { messages, model, temperature } = req.body
    const userMessage = messages[messages.length - 1].content // 获取用户最新的消息
    const connection = await pool.getConnection()

    try {
      // 创建新的聊天
      const [result] = await connection.query(
        'INSERT INTO chats (user_id, title) VALUES (?, ?)',
        [req.user.userId, userMessage.slice(0, 50)]
      )
      const currentChatId = result.insertId

      // 保存用户消息
      await connection.query(
        'INSERT INTO messages (chat_id, role, content) VALUES (?, ?, ?)',
        [currentChatId, 'user', userMessage]
      )

      // 调用AI接口
      const aiResponse = await deepseekService.chatCompletion(userMessage)

      // 保存AI回复
      await connection.query(
        'INSERT INTO messages (chat_id, role, content) VALUES (?, ?, ?)',
        [currentChatId, 'assistant', aiResponse]
      )

      // 更新聊天时间
      await connection.query(
        'UPDATE chats SET updated_at = CURRENT_TIMESTAMP WHERE id = ?',
        [currentChatId]
      )

      res.json({
        code: 200,
        message: '发送成功',
        success: true,
        data: {
          chatId: currentChatId,
          choices: [{
            message: {
              content: aiResponse
            }
          }]
        }
      })
    } finally {
      connection.release()
    }
  } catch (err) {
    console.error('聊天错误:', err)
    res.status(500).json({
      code: 500,
      message: err.message || '发送消息失败',
      success: false
    })
  }
})

// 删除单个会话
router.delete('/conversation/:chatId', auth, async (req, res) => {
  try {
    const chatId = req.params.chatId
    const userId = req.user.userId

    const result = await Chat.deleteConversation(chatId, userId)

    if (result.success) {
      res.json({
        code: 200,
        message: result.message,
        success: true
      })
    } else {
      res.status(404).json({
        code: 404,
        message: result.message,
        success: false
      })
    }
  } catch (error) {
    console.error('删除会话失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器错误，删除失败',
      success: false
    })
  }
})

// 批量删除会话
router.post('/conversations/delete', auth, async (req, res) => {
  try {
    const { chatIds } = req.body

    if (!chatIds || !Array.isArray(chatIds) || chatIds.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '无效的会话ID列表',
        success: false
      })
    }

    const result = await Chat.deleteMultipleConversations(chatIds, req.user.userId)

    if (result.success) {
      res.json({
        code: 200,
        message: result.message,
        success: true,
        data: {
          deleted: result.deleted,
          notDeleted: result.notDeleted
        }
      })
    } else {
      res.status(400).json({
        code: 400,
        message: result.message,
        success: false
      })
    }
  } catch (error) {
    console.error('批量删除会话失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器错误，批量删除失败',
      success: false
    })
  }
})

module.exports = router
